#include "../mq_server/bind.h"
#include <gtest/gtest.h>
using namespace ns_bind;

shared_ptr<BindManage> bmp;

class BindTest : public testing::Environment
{
public:
    virtual void SetUp() override
    {
        bmp = make_shared<BindManage>("test/bind.db");
    }

    virtual void TearDown() override
    {
        // qmp->clear();
    }
};

TEST(BindTest, insert_test)
{
    bmp->bind("e1", "q1", "xxx", true);
    bmp->bind("e1", "q2", "ttt", true);
    bmp->bind("e2", "q2", "yyy", true);
    bmp->bind("e3", "q3", "zzz", true);
    bmp->bind("e3", "q2", "ggg", true);
    bmp->bind("e3", "q1", "kkk", true);
    ASSERT_EQ(bmp->size(), 6);
}

TEST(BindTest, recovery_test)
{
    ASSERT_EQ(bmp->exist("e1", "q1"), true);
    ASSERT_EQ(bmp->exist("e1", "q2"), true);
    ASSERT_EQ(bmp->exist("e2", "q2"), true);
    ASSERT_EQ(bmp->exist("e3", "q3"), true);
    ASSERT_EQ(bmp->exist("e3", "q2"), true);
    ASSERT_EQ(bmp->exist("e3", "q1"), true);
}

TEST(BindTest, get_test)
{
    ASSERT_EQ(bmp->exist("e3", "q2"), true);
    shared_ptr<Bind> bp = bmp->get_bind("e3", "q2");
    ASSERT_NE(bp.get(), nullptr);
    ASSERT_EQ(bp->_binding_key, string("ggg"));
    ASSERT_EQ(bp->_durable, true);
    ASSERT_EQ(bp->_exchange_name, "e3");
    ASSERT_EQ(bp->_queue_name, "q2");

    QueueBindMapPtr qbp = bmp->get_exchange_bind("e1");
    ASSERT_NE(qbp.get(), nullptr);
    ASSERT_EQ(qbp->size(), 2);
    ASSERT_EQ(qbp->operator[]("q2")->_binding_key, "ttt");
    ASSERT_EQ(qbp->operator[]("q2")->_durable, true);
}

TEST(BindTest, delete_test)
{
    bmp->delete_exchange("e1");
    ASSERT_EQ(bmp->size(), 4);

    bmp->delete_queue("q2");
    ASSERT_EQ(bmp->size(), 2);

    bmp->unbind("e3", "q3");
    ASSERT_EQ(bmp->size(), 1);

    QueueBindMapPtr quebindp = bmp->get_exchange_bind("e3");
    ASSERT_EQ(quebindp->operator[]("q1")->_binding_key, "kkk");
}

int main(int argc, char *argv[])
{
    testing::InitGoogleTest(&argc, argv);
    testing::AddGlobalTestEnvironment(new BindTest);

    return RUN_ALL_TESTS();
}